<template>
  <div v-if="visible"
       class="edit-tag-dialog">
    <el-dialog width="660px"
               :visible.sync="visible"
               @close="dialogClose"
               :close-on-click-modal="false"
               title="设置标签">
      <div class="edit-tag-container">
        <div class="tags-container">
          <h2 class="title">
            标签库
            <span>{{tagsList.length}}</span>
          </h2>
          <div class="tags-list-container">
            <ul v-if="dialogStatus==='addUserTag'"
                class="tags-list">
              <li v-for="(item, index) in tagsList"
                  @click="chooseTag(item, index)"
                  :key="index"
                  :class="{ 'active': item.is_choosed }"
                  class="tags-item">
                <i v-if="!item.is_choosed"
                   class="fa fa-plus"></i>
                <i v-if="item.is_choosed"
                   class="fa fa-check"></i>
                <i @click="
                    e => {
                      deleteTag(e, item);
                    }
                  "
                   class="close-icon fa fa-times-circle"></i>
                {{ item.sign_name }}
              </li>
            </ul>
            <ul v-if="dialogStatus==='addFileTag'"
                class="tags-list">
              <li v-for="(item, index) in tagsList"
                  @click="chooseTag(item, index)"
                  :key="index"
                  :class="{ 'active': item.file_used }"
                  class="tags-item">
                <i v-if="!item.file_used"
                   class="fa fa-plus"></i>
                <i v-if="item.file_used"
                   class="fa fa-check"></i>
                {{ item.sign_name }}
              </li>
            </ul>
          </div>
        </div>
        <div class="tags-container">
          <h2 class="title">
            {{
              dialogStatus === "addFileTag" ? "设置文件标签" : "设置标签过滤"
            }}
            <span v-if="dialogStatus==='addFileTag'">{{fileTagList.length}}/10</span>
            <span v-if="dialogStatus==='addUserTag'">{{userTagList.length}}</span>
          </h2>
          <div class="tags-list-container">
            <div class="add-tag">
              <el-input v-model="tagName"
                        placeholder="请输入标签名"></el-input>
              <el-button @click="addTag"
                         class="add-tag-btn">添加</el-button>
            </div>
            <ul v-if="dialogStatus === 'addFileTag'"
                class="tags-list">
              <li class="tags-item active"
                  v-for="(item, index) in fileTagList"
                  :key="index">
                {{ item.sign_name }}
                <i @click="removeTag(item, index)"
                   class="fa fa-times-circle"></i>
              </li>
            </ul>
            <ul v-if="dialogStatus === 'addUserTag'"
                class="tags-list">
              <li class="tags-item active"
                  v-for="(item, index) in userTagList"
                  :key="index">
                {{ item.sign_name }}
                <i @click="removeTag(item, index)"
                   class="fa fa-times-circle"></i>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div slot="footer"
           class="dialog-footer align-center">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button @click="editTag"
                   type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { ProjectFileApi } from '@/services/ProjectCenter'
export default {
  data () {
    return {
      visible: false,
      // 标签库标签列表
      tagsList: [],
      // 文件已选择标签列表
      fileTagList: [],
      // 用户已选择标签列表
      userTagList: [],
      // 添加标签时输入框内容
      tagName: '',

      // 选择标签时以标签id为键存储标签对象
      choosedTagMap: new Map()
    }
  },
  props: {
    dialogVisible: {
      type: Boolean
    },
    // 区分是为文件添加标签还是管理标签列表状态
    dialogStatus: {
      type: String,
      default: 'addFileTag'
    },
    dialogForm: {
      type: Object
    },

    fileId: {
      type: Number,
      default: 0
    },
    // 文件所属标签列表
    fileSign: {
      type: Array,
      default: () => {
        return []
      }
    },
    callback: {
      type: Function
    }
  },
  watch: {
    dialogVisible (newval) {
      console.log('watch visible', this.fileSign)
      this.visible = newval
      if (newval) {
        if (this.dialogStatus === 'addFileTag') {
          this.fileTagList = JSON.parse(JSON.stringify(this.fileSign))
          this.getTagList('')
        } else {
          this.getTagList('1')
        }
      }
    },
    dialogForm: {
      handler (newval) { },
      deep: true
    },
    fileId: {
      handler (newval) {
        console.log(newval, 'watch file id')
        // this.getTagList('')
      },
      deep: true
    },
    fileSign: {
      handler (newval) {
        console.log(newval, 'watch file sign')
        this.fileTagList = JSON.parse(JSON.stringify(newval))
      },
      deep: true
    }
  },
  methods: {
    // 选择标签
    chooseTag (item, index) {
      if (this.dialogStatus === 'addFileTag') {
        if (this.fileTagList.length < 10) {
          if (!item.file_used) {
            item.file_used = !item.file_used
            this.fileTagList.unshift(item)
          }
        } else {
          this.$message.warning('最多设置10个标签')
        }
      } else if (this.dialogStatus === 'addUserTag') {
        if (!item.is_choosed) {
          item.is_choosed = !item.is_choosed
          this.userTagList.unshift(item)
        }
      }
    },
    removeTag (item, index) {
      // 根据当前状态删除用户标签列表或是文件标签列表中的元素
      if (this.dialogStatus === 'addFileTag') {
        let choosedTag = this.choosedTagMap.get(item.p_project_doc_file_sign_id)
        choosedTag.file_used = 0
        this.fileTagList.splice(index, 1)
      } else {
        let choosedTag = this.choosedTagMap.get(item.p_project_doc_file_sign_id)
        choosedTag.is_choosed = 0
        this.userTagList.splice(index, 1)
      }
    },
    // 移除为文件添加的标签
    dialogClose () {
      this.tagName = ''
      this.$emit('update:dialogVisible', false)
    },
    // 添加标签
    addTag () {
      if (this.tagName === '') {
        this.$message.warning('请输入标签名')
      } else {
        ProjectFileApi.createTag({
          data: {
            sign_params: [{ sign_name: this.tagName }]
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('添加标签成功')
            this.getTagList('')
          }
        })
      }
    },
    // 从标签库中删除标签
    deleteTag (e, item) {
      console.log(e, item, 'remove tag')
      e.stopPropagation()
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteTagApi(item.p_project_doc_file_sign_id)
        })
        .catch(() => { })
    },
    // 调用删除标签接口
    deleteTagApi (id) {
      ProjectFileApi.deleteTag({
        data: {
          id: id
        }
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('删除标签成功')
          if (this.dialogStatus === 'addUserTag') {
            for (let i = 0; i < this.userTagList.length; i++) {
              let item = this.userTagList[i]
              if (item.p_project_doc_file_sign_id === id) {
                this.userTagList.splice(i, 1)
              }
            }
          }
          this.getTagList('')
        }
      })
    },
    // 获取单位下所有标签或当前用户所属标签，通过type区分，type为空获取单位，为1获取用户
    getTagList (type) {
      return ProjectFileApi.getTagList({
        params: {
          only_user: type,
          file_id: this.dialogStatus === 'addFileTag' ? this.fileId : 0
        }
      }).then(res => {
        if (res.code === 0) {
          if (type === '') {
            this.tagsList = res.data.list
            this.tagsList.map((item) => {
              this.choosedTagMap.set(item.p_project_doc_file_sign_id, item)
            })
          } else if (type === '1') {
            this.userTagList = res.data.list
            console.log(this.userTagList, 'user tag list')
          }
        }
      })
    },
    // 根据状态调用保存用户标签列表接口或是保存文件标签列表接口
    editTag () {
      if (this.dialogStatus === 'addFileTag') {
        this.editFileTag()
      } else if (this.dialogStatus === 'addUserTag') {
        this.editUserTag()
      }
    },
    // 保存用户标签列表
    async editUserTag () {
      let list = []
      if (this.userTagList.length === 0) {
        this.$message.warning('请选择至少一个标签')
      } else {
        this.userTagList.map(item => {
          list.push({
            sign_id: item.p_project_doc_file_sign_id
          })
        })
        ProjectFileApi.editUserTagList({
          data: {
            sign_ids: list
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('保存成功')
            // this.getTagList('')
            // this.getTagList('1')
            this.$emit('callback', '')
            this.dialogClose()
          }
        })
      }
    },
    // 保存文件标签列表
    editFileTag () {
      let list = []
      if (this.fileTagList.length === 0) {
        this.$message.warning('请选择至少一个标签')
      } else {
        this.fileTagList.map((item) => {
          list.push(item.p_project_doc_file_sign_id)
        })
        ProjectFileApi.editFileTag({
          data: {
            id: this.fileId,
            sign_ids: list
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('编辑文件标签成功')
            this.$emit('callback', '')
            this.dialogClose()
          }
        })
      }
    }
  },
  created () {
    this.getTagList('')
    this.getTagList('1')
  },
  mounted () {
    console.log('mouted')
  }
}
</script>
<style scoped lang="scss">
.edit-tag-dialog {
  .edit-tag-container {
    display: flex;
    justify-content: space-between;
    .tags-container {
      width: 285px;
      height: 375px;
      border: 1px solid #bfbfbf;
      display: flex;
      flex-direction: column;
      .title {
        width: 100%;
        height: 48px;
        padding: 0 20px;
        background-color: #f5f5f5;
        border: 1px solid #bfbfbf;
        border-left: 0;
        border-right: 0;
        border-top: 0;
        line-height: 48px;
        font-size: 16px;
        color: #333;
        display: flex;
        justify-content: space-between;
        span {
          color: #999;
          font-size: 12px;
          text-align: right;
        }
      }
      .tags-list-container {
        padding: 20px;
        overflow-y: scroll;
        .tags-list {
          display: flex;
          justify-content: flex-start;
          flex-wrap: wrap;
          position: relative;
          .tags-item {
            width: auto;
            height: 36px;
            line-height: 36px;
            padding: 0 12px;
            border: 1px solid #1890ff;
            background-color: #fff;
            color: #1890ff;
            font-size: 14px;
            border-radius: 4px;
            margin-bottom: 8px;
            margin-right: 8px;
            cursor: pointer;
            position: relative;
            &.active {
              color: #fff;
              background-color: #1890ff;
            }
            .close-icon {
              position: absolute;
              top: -8px;
              right: -6px;
              width: 12px;
              height: 12px;
              border-radius: 50%;
              // background-image: url("../../../assets/close.png");
              color: #bfbfbf;
              z-index: 9999;
              background-color: #fff;
              cursor: pointer;
            }
          }
        }
        .add-tag {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
          .el-input {
            width: 158px;
          }
          .el-button {
            width: 68px;
            height: 40px;
            border: 1px solid #1890ff;
            color: #1890ff;
          }
        }
      }
    }
  }
}
</style>
